import { mapSecret } from "@/config"
import { loadScript, getUrlParams } from "@/utils/utils"

// 本地缓存的key
const localCacheNames = ["settingButtonPosition", "debug", "developMode"]
const sessionCacheNames = []

export default {
  state: {
    debug: false, // 调试模式
    developMode: false, // 开发模式
    mapSecret: mapSecret, // 地图密钥
    settingButtonPosition: { x: 0, y: 400 } // 设置组件按钮位置信息
  },
  getters: {
    debug: (state) => state.debug, // 调试模式
    developMode: (state) => state.developMode, // 开发模式
    mapSecret: (state) => state.mapSecret, // 地图密钥
    settingButtonPosition: (state) => state.settingButtonPosition
  },
  mutations: {
    // 自动初始化
    INIT(state) {
      // 初始化本地缓存
      localCacheNames.forEach((name) => {
        let data = uni.getStorageSync(name)
        if (data) state[name] = data
      })
      // #ifdef WEB
      sessionCacheNames.forEach((name) => {
        let data = window.sessionStorage.getItem(name)
        if (data) state[name] = data
      })
      // #endif
    },
    // 设置地图密钥
    SET_MAP_SECRET(state, data) {
      state.mapSecret = data
    },
    // 设置按钮位置
    SET_SETTING_BUTTON_POSITION(state, data) {
      state.settingButtonPosition = data
      uni.setStorageSync("settingButtonPosition", data)
    },
    // 设置调试模式
    SET_DEBUG(state, data) {
      state.debug = data
      uni.setStorageSync("debug", data)
    },
    // 设置开发模式
    SET_DEVELOP_MODE(state, data) {
      state.developMode = data
    }
  },
  actions: {
    init({ state, dispatch }) {
      const { debug } = getUrlParams()
      if (debug || state.debug) dispatch("enableDebug")
    },
    enableDebug({ commit }) {
      commit("SET_DEBUG", true)
      loadScript("https://public-oss-file.zmaxfilm.com/zuimei-film-oss/js/eruda.js").then(() => {
        window._eruda = eruda
        window._eruda.init()
      })
    },
    // 设置地图密钥
    setMapSecret({ commit }, data) {
      commit("SET_MAP_SECRET", data)
    }
  }
}
